package cn.xyinping._01_hello;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author 27266
 * @desrciption 消费者
 * @date 2021/11/12
 */
public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 创建RabbitMQ链接
        ConnectionFactory factory  = new ConnectionFactory();
        Connection connection = factory.newConnection();
        // 2. 创建通道
        Channel channel = connection.createChannel();
        // 消息处理回调
        // 全限定名防止冲突
        com.rabbitmq.client.Consumer callback = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, // 信封
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                System.out.println("消息"+new String(body));
//                int  i=1/0;
                System.out.println("consumerTag"+consumerTag);
                System.out.println("交换机"+envelope.getExchange());
                System.out.println("队列" +envelope.getRoutingKey());
                System.out.println("消息的Id"+envelope.getDeliveryTag());
                // 手动签收
                channel.basicAck(envelope.getDeliveryTag(), // 消息Id
                        false); // 是否签收多个消息
            }
        };
        // 3.监听队列
       channel.basicConsume(Producer.QUEUE, // 队列名
               false, // 是否自动签收  如果消息消费失败可能会导致消息丢失，改成手动签收
                callback); // 消息处理回调
    }

}
